package chapter7;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/addCustomer.do")
public class AddCustomerServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		
		
		String message = null;
		try {
			/*customer.setCust_id(request.getParameter("cust_id"));
			// 将传递来的字符串重新使用utf-8编码，以免Tomcat7 GET方式产生乱码
			customer.setCname(new String(request.getParameter("cname")
					.getBytes("iso-8859-1"), "UTF-8"));
			customer.setEmail(new String(request.getParameter("email")
					.getBytes("iso-8859-1"), "UTF-8"));
			customer.setBalance(Double.parseDouble(request
					.getParameter("balance")));*/
			String cusId = request.getParameter("cust_id");
			String cusName = request.getParameter("cname");
			String cusEmail = request.getParameter("email");
			String cusBalance = request.getParameter("balance");
			
			Customer customer = new Customer();
			customer.setCust_id(cusId);
			customer.setCname(cusName);
			customer.setEmail(cusEmail);
			customer.setBalance(Double.parseDouble(cusBalance));
			
			CustomerDao dao = new CustomerDao();
			boolean success = dao.addCustomer(customer);
			
			if (success) {
				message = "<li>成功插入一条记录！</li>";
			} else {
				message = "<li>插入记录错误！</li>";
			}
		} catch (Exception e) {
			message = "<li>插入记录错误！</li>";
		}
		request.setAttribute("result", message);
		
		RequestDispatcher rd = getServletContext().getRequestDispatcher(
				"/showCustomers");
		rd.forward(request, response);
	}
}
